#include <Arduino.h>
#include <WiFi.h>
#include <WiFiMulti.h>
#include <WiFiClientSecure.h>
#include <WebSocketsClient.h>
#include <ArduinoJson.h>
#include <IRremoteESP8266.h>
#include <IRsend.h>
#include <ir_Gree.h>

// 网络设置
const char* ssid = "EthanAP";
const char* password = "2247102148";
const char* server_ip = " 服务器IP";  // 服务器IP
const int server_port = 8080;            // 服务器端口

// IR设置
const uint16_t kIrLed = 4;  // D2引脚用于IR发射
IRGreeAC ac(kIrLed);        // 格力空调遥控器实例

WebSocketsClient webSocket;
unsigned long lastPing = 0;
bool isConnected = false;

// 处理WebSocket事件
void webSocketEvent(WStype_t type, uint8_t * payload, size_t length) {
  switch(type) {
    case WStype_DISCONNECTED:
      Serial.printf("[WS] 断开连接!\n");
      isConnected = false;
      break;
      
    case WStype_CONNECTED:
      Serial.printf("[WS] 已连接到服务器\n");
      isConnected = true;
      // 发送注册消息，标识为空调控制设备
      webSocket.sendTXT("register:ac_device");
      // 请求当前状态
      webSocket.sendTXT("get_status");
      break;
      
    case WStype_TEXT:
      Serial.printf("[WS] 收到: %s\n", payload);
      handleMessage(payload, length);
      break;
      
    case WStype_ERROR:
      Serial.printf("[WS] 发生错误\n");
      break;
  }
}

// 处理收到的消息
void handleMessage(uint8_t * payload, size_t length) {
  // 解析JSON消息
  DynamicJsonDocument doc(1024);
  DeserializationError error = deserializeJson(doc, payload, length);
  
  if (error) {
    Serial.print("[JSON] 解析失败: ");
    Serial.println(error.c_str());
    return;
  }

  // 检查是否为空调状态消息
  if (doc.containsKey("switch")) {
    bool acOn = doc["switch"];
    const char* acMode = doc["mode"];
    int acTemp = doc["temp"];
    int acFan = doc["fan"];
    bool acVSwing = doc["vf"];
    bool acLight = doc["light"];
    bool acSleep = doc["sleep"];
    bool acTurbo = doc["turbo"];
    
    Serial.println("接收到空调设置:");
    Serial.printf("电源: %s\n", acOn ? "开" : "关");
    Serial.printf("模式: %s\n", acMode);
    Serial.printf("温度: %d\n", acTemp);
    Serial.printf("风速: %d\n", acFan);
    
    // 应用设置到格力空调遥控器
    if (acOn) {
      ac.on();
    } else {
      ac.off();
    }
    
    // 设置模式
    if (strcmp(acMode, "kGreeCool") == 0) {
      ac.setMode(kGreeCool);
    } else if (strcmp(acMode, "kGreeHeat") == 0) {
      ac.setMode(kGreeHeat);
    } else if (strcmp(acMode, "kGreeDry") == 0) {
      ac.setMode(kGreeDry);
    } else if (strcmp(acMode, "kGreeFan") == 0) {
      ac.setMode(kGreeFan);
    } else if (strcmp(acMode, "kGreeAuto") == 0) {
      ac.setMode(kGreeAuto);
    }
    
    // 设置温度
    ac.setTemp(acTemp);
    
    // 设置风速
    ac.setFan(acFan);
    
    // 设置垂直摆风
    ac.setSwingVertical(acVSwing, kGreeSwingAuto);
    
    // 设置其他选项
    ac.setLight(acLight);
    ac.setSleep(acSleep);
    ac.setTurbo(acTurbo);
    
    // 发送IR命令
    Serial.println("发送IR信号到空调...");
    ac.send();
    
    // 打印当前状态
    printState();
  }
}

// 打印空调遥控器当前状态
void printState() {
  Serial.println("格力空调遥控器状态:");
  Serial.printf("  %s\n", ac.toString().c_str());
  
  unsigned char* ir_code = ac.getRaw();
  Serial.print("红外码: 0x");
  for (uint8_t i = 0; i < kGreeStateLength; i++)
    Serial.printf("%02X", ir_code[i]);
  Serial.println();
}

void setup() {
  Serial.begin(115200);
  delay(1000);
  
  Serial.println("\n初始化...");
  
  // 初始化IR发射器
  ac.begin();
  
  // 连接WiFi
  WiFi.begin(ssid, password);
  Serial.print("连接到WiFi ");
  Serial.print(ssid);
  
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  
  Serial.println("\nWiFi已连接");
  Serial.print("IP地址: ");
  Serial.println(WiFi.localIP());
  
  // 设置WebSocket客户端
  webSocket.begin(server_ip, server_port, "/");
  webSocket.onEvent(webSocketEvent);
  webSocket.setReconnectInterval(5000); // 5秒重连
}

void loop() {
  webSocket.loop();
  
  // // 每1秒发送一次 get_status 请求
  // unsigned long now = millis();
  // if (isConnected && now - lastPing > 1000) {
  //   webSocket.sendTXT("get_status");
  //   lastPing = now;
  // }
  
  // // 防止millis()溢出
  // if (now < lastPing) {
  //   lastPing = now;
  // }
}